package org.grow.erp.controller;

import org.grow.erp.dao.FoodBillRepository;
import org.grow.erp.entity.FoodBill;
import org.grow.erp.entity.FoodBillItem;
import org.grow.erp.entity.OutStockBill;
import org.grow.support.service.CodeGene;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Optional;

/**
 * @Author: xwg
 * @CreateDate: 2022/4/28
 */
@RequestMapping("/erp/foodBill")
@RestController
public class FoodBillController {
    @Autowired
    private ThreadLocal<CodeGene> codeGeneThreadLocal;
    @Autowired
    private FoodBillRepository foodBillRepository;

    @PostMapping("/insert")
    public FoodBill insert(@RequestBody FoodBill foodBill) {
        String fb = codeGeneThreadLocal.get().nextCode("FB");
        foodBill.setFoodBillCode(fb);
        foodBill.setFbUTime(LocalDateTime.now());
        foodBill.refreshDomainRelationship();
        foodBill.refreshComputedFields();

        FoodBill save = foodBillRepository.save(foodBill);

        return save;
    }

    @PutMapping("/modify")
    public FoodBill modify(@RequestBody FoodBill foodBill) {
        foodBillRepository.findById(foodBill.getFoodBillCode()).ifPresent(x -> {
            foodBill.refreshDomainRelationship();
            foodBill.refreshComputedFields();
            foodBill.setFbUTime(LocalDateTime.now());
            foodBillRepository.save(foodBill);
        });
        return foodBill;
    }

    @GetMapping("/find/{code}")
    public Optional<FoodBill> find(@PathVariable("code") String code) {
        Optional<FoodBill> byId = foodBillRepository.findById(code);
        return byId;
    }
}
